package cn.zgf.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author GaoFeng2017
 * @date 2018-02-20 14:23:15
 **/

public class POJOUtils {
    /**
     * 将一个string bean中的数据复制到另一个实体bean中
     **/
    public static void copyBean(Object beanDest,Object beanSrc) {
        /*注册一个字符串与日期的转换器*/
        ConvertUtils.register(new Converter() {
            @Override
            public Object convert(Class aClass, Object o) {
                String str = (String)o;
                if (str == null || str.trim().equals("")) {
                    return null;
                }
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date = sf.parse(str);
                    return date;
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }, Date.class);
        try {
            BeanUtils.copyProperties(beanSrc,beanDest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
